﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    public class CloudCardsController : BaseController
    {
        #region 列表
        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Listing(int draw, int start, int length, string keyWord = "", int cateId = 0, int status = -1,  string shopName = "")
        {
            try
            {
                int order;
                int.TryParse(Request["order[0][column]"], out order);
                var direction = Request["order[0][dir]"];
                var orderByColumns = new[] { "CardName", "CardCategoryId", "PassStatus", "ShopId" };
                var shopIds = string.Empty;
                if (!string.IsNullOrEmpty(shopName))
                {
                    var shopList = ShopsBLL.Instance.GetListByName(shopName);
                    shopIds = shopList.Count > 0 ? string.Join(",", shopList.Select(l => l.Id)) : "-1";
                }
                var list = CloudCardsBLL.Instance.GetPagingList(draw, (start / length) + 1, length, SqlSafe(keyWord), cateId, status, shopIds, orderByColumns[order] + " " + direction, true);
                return Json(list);
            }
            catch (Exception ex)
            {
                Logger.Error("CloudCards Listing Catch Error: " + ex.Message);
                return Json(false);
            }
        }
        #endregion

        #region 修改
        public ActionResult Update(int id)
        {
            if (id <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var model = CloudCardsBLL.Instance.GetModel(id);
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }
            var cate = CardCategoryBLL.Instance.GetModel(model.CardCategoryId);
            if (cate != null)
            {
                model.CategoryName = cate.CategoryName;
            }
            var shop = ShopsBLL.Instance.GetModel(model.ShopId);
            if (shop != null)
            {
                model.ShopName = shop.Name;
            }
            InitiSet();
            ViewBag.theHeadPic = ConfigurationManager.AppSettings["ImgFileSitePath"] + model.LoGo;
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, CloudCards model)
        {
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var tempModel = CloudCardsBLL.Instance.GetModel(model.Id);
            if (tempModel == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (tempModel.PassStatus != (int) CloudCardEnum.CloudCardsPassStatus.待审核)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var strUploadImage = UploadImage("fileImage", "/CloudCards/Logo/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage))
            {
                model.LoGo = strUploadImage;
            }
            tempModel.TotalQuantity = model.TotalQuantity;
            tempModel.LoGo = model.LoGo;
            tempModel.StartTime = model.StartTime;
            tempModel.EndTime = model.EndTime;
            tempModel.CanShare = model.CanShare;
            if (CloudCardsBLL.Instance.Update(tempModel))
            {
                return RedirectToAction("List");
            }
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }
        #endregion

        #region 删除
        [HttpPost]
        public JsonResult Delete()
        {
            var result = CloudCardsBLL.Instance.DeleteList(Request["doIds"]);
            return Json(result);
        }
        #endregion

        #region 其他
        /// <summary>
        /// 卡券审核
        /// </summary>
        public ActionResult Pass(int id, int action)
        {
            var result = new Result();
            var model = CloudCardsBLL.Instance.GetModel(id);
            if (model == null || model.PassStatus != (int)CloudCardEnum.CloudCardsPassStatus.待审核)
            {
                result.Message = "数据有误，请刷新再试";
                return Json(result);
            }
            model.PassStatus = action == 1 ? (int)CloudCardEnum.CloudCardsPassStatus.审核通过 : (int)CloudCardEnum.CloudCardsPassStatus.审核未通过;
            model.PassTime = DateTime.Now;
            model.PassUserId = CurrentUser.Id;
            result.Status = CloudCardsBLL.Instance.Update(model);
            if (result.Status == false)
            {
                result.Message = "审核失败，请重试";
            }
            return Json(result);
        }

        private void InitiSet()
        {
            var canShare = new List<SelectListItem>
            {
                new SelectListItem { Value = "true", Text = "是" },
                new SelectListItem { Value = "false", Text = "否" }
            };
            ViewBag.CanShare = canShare;
        }
        #endregion
    }
}
